#pragma once
#include <iostream>
#include "nocopy.hpp"
#include <string>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include "comm.hpp"
#include"Log.hpp"
// 网络编程常用头文件
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

const static uint16_t default_port = 8888;
const static int default_fd = -1;
class UdpServer : public NoCopy // 继承了NoCopy类;
{
public:
    UdpServer(const std::string &ip, uint16_t port = default_port)
        : _ip(ip), _port(port), _sock_fd(default_fd)
    {
    }
    ~UdpServer()
    {
    }
    void Init()
    {
        _sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sock_fd < 0)
        {
            // 出错信息，打日志

            lg.LogMessage(Fatal, "socket error, %d : %s\n", errno, strerror(errno));
            exit(Socket_Err);
        }
        lg.LogMessage(Info, "success to init the socket, socket_fd: %d", _sock_fd);

        // 填充sockaddr结构体对象
        struct sockaddr_in local;
        bzero(&local, sizeof(local)); // 初始化结构体

        local.sin_family = AF_INET;                     // 绑定网络通信
        local.sin_port = htons(_port);                  // 绑定端口
        local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 绑定ip

        // 绑定指定网络信息和指定的文件系统
        int n = ::bind(_sock_fd, (struct sockaddr *)&local, sizeof(local));
        if (n != 0)
        {
            lg.LogMessage(Fatal, "Bind error, %d : %s", errno, strerror(errno));
            exit(Bind_Err);
        }
        // 成功绑定
        lg.LogMessage(Info, "Bind success");
    }
    void Start()
    {
        // buffer receive
        char buff_r[1024];

        // 服务器启动时，不退出
        while (1)
        {


            sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sock_fd, buff_r, sizeof(buff_r) - 1, 0, (struct sockaddr*)&peer, &len);
            if(n>0)
            {
                buff_r[n] = 0;
                std::cout<<"client say: "<<buff_r<<std::endl;
                // 服务器向客户端发送信息
                sendto(_sock_fd, buff_r, sizeof(buff_r) - 1, 0, (struct sockaddr*)&peer, len);
            }
        }
    }

private:
    std::string _ip;
    uint16_t _port;
    int _sock_fd;
};